<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>分类参数</el-breadcrumb-item>
        </el-breadcrumb>
         <!-- 卡片列表 -->
         <el-card>
             <el-alert
                title="注意:只允许为第三级分类设置相关参数"
                :closeable="false"
                type="warning" show-icon>
            </el-alert>
            <div class="selectCate">
                <span>选择商品分类：</span>
              <!-- v-model用来指定默认的选中 
          option：指定要渲染的数据-->
          <el-cascader
          v-model="cascaderValue"
          :options="cateList"
          :props="cascaderSetProps"
          @change="cascaderChange"
           clearable></el-cascader>
            </div>
             <el-tabs v-model="activeName" @tab-click="tabClick">
    <el-tab-pane label="动态参数" name="many">
        <el-button type="primary" size="mini" :disabled="isdisabled" @click="addParamDialogVisible=true">添加参数</el-button>
    <!-- 动态参数表格 -->
    <el-table :data="manyTableData" border stripe>
      <!-- 展开行 -->
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-tag v-for="(item,i) in scope.row.attr_vals" :key="item.id" closable @close="closeParamTag(scope.row,i)">{{item}}</el-tag>
          <el-input
          class="input-new-tag"
          v-if="scope.row.inputVisible"
          v-model="scope.row.inputValue"
          ref="saveTagInput"
          size="small"
          @keyup.enter.native="handleInputConfirm(scope.row)"
          @blur="handleInputConfirm(scope.row)"
        >
        </el-input>
        <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
        </template>
      </el-table-column>
      <!-- 索引列 -->
      <el-table-column type="index"></el-table-column>
      <el-table-column label="参数名称" prop="attr_name"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditParamDialog(scope.row.attr_id)">编辑</el-button>
          <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteParamById(scope.row.attr_id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    </el-tab-pane>
    <el-tab-pane label="静态属性" name="only">
        <el-button type="primary" size="mini" :disabled="isdisabled" @click="addParamDialogVisible=true">添加属性</el-button>
        <!-- 静态参数表格 -->
        <el-table :data="onlyTableData" border stripe>
        <!-- 展开行 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
          <el-tag v-for="(item,i) in scope.row.attr_vals" :key="item.id" closable @close="closeParamTag(scope.row,i)">{{item}}</el-tag>
          <el-input
          class="input-new-tag"
          v-if="scope.row.inputVisible"
          v-model="scope.row.inputValue"
          ref="saveTagInput"
          size="small"
          @keyup.enter.native="handleInputConfirm(scope.row)"
          @blur="handleInputConfirm(scope.row)"
        >
        </el-input>
        <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
        </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="参数名称" prop="attr_name"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditParamDialog(scope.row.attr_id)">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteParamById(scope.row.attr_id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-tab-pane>
  </el-tabs>
         </el-card>

         <!-- 添加参数的对话框 -->
         <el-dialog
            :title="'添加'+title"
            :visible.sync="addParamDialogVisible"
            width="30%"
            @close="addParamClose">
            <!-- 内容部分 -->
            <!-- 添加表单 -->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
              <el-form-item :label="title" prop="attr_name">
                <el-input v-model="addForm.attr_name"></el-input>
              </el-form-item>
            </el-form>
            <!-- 尾部部分 -->
            <span slot="footer" class="dialog-footer">
              <el-button @click="addParamDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="submitAddParam">确 定</el-button>
            </span>
          </el-dialog>
    
    <!-- 编辑参数 -->
     <el-dialog
            :title="'编辑'+title"
            :visible.sync="editParamDialogVisible"
            width="30%"
            @close="editParamClose">
            <!-- 内容部分 -->
            <!-- 添加表单 -->
            <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="100px">
              <el-form-item :label="title" prop="attr_name">
                <el-input v-model="editForm.attr_name"></el-input>
              </el-form-item>
            </el-form>
            <!-- 尾部部分 -->
            <span slot="footer" class="dialog-footer">
              <el-button @click="editParamDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="submitEditParam()">确 定</el-button>
            </span>
          </el-dialog>
    </div>
</template>

<script>
export default {
  data() {
    return {
    cateList:[],
    cascaderValue:[],
    cascaderSetProps:{
        expandTrigger:'hover',
        label:"cat_name",
        value:"cat_id"
    },
    // 选项卡数据绑定
    activeName:"many",
    // 动态参数列表
    manyTableData:[],
    // 静态参数列表
    onlyTableData:[],
    // 是否显示添加参数对话框
    addParamDialogVisible:false,
    // 添加参数form
    addForm:{
      attr_name:''
    },
    // 添加参数验证属性
    addFormRules:{
      attr_name:[
         { required: true, message: '请输入参数值', trigger: 'blur' }
      ]
    },
    // 编辑参数form
    editForm:{
      attr_name:''
    },
    // 控制显示编辑参数对话框
    editParamDialogVisible:false
    
    }
   

  },

  created() {
    this.getCateList()
  },

  methods: {
    //   获取商品分类数据
    async getCateList(){
        const {data:res}=await this.$axios.get('categories')
        if(res.meta.status!=200) return this.$message.error('获取失败')
        this.cateList=res.data
    },
    // 获取参数列表
    async getParams(){
      if(this.cascaderValue.length!=3){
            this.cascaderValue=[];
            this.manyTableData=[];
            this.onlyTableData=[];
            return;
       }
        const {data:res}=await this.$axios.get(`categories/${this.cateId}/attributes`,{params:{sel:this.activeName}})
        if(res.meta.status!=200) return this.$message.error('获取数据失败')
        res.data.forEach(ele => {
            ele.attr_vals=ele.attr_vals==''?[]:ele.attr_vals.split(' ');
            ele.inputVisible=false;
            ele.inputValue='';
          });
        if(this.activeName=="many")
        {
          this.manyTableData=res.data
        }else
        {
          this.onlyTableData=res.data
        }
    },
    // 级联选项变化事件
    cascaderChange(){
       this.getParams();
        
    },
    //切换卡切换事件
    tabClick(){
      this.getParams();
    },
    // 关闭添加参数对话框
    addParamClose(){
     this.$refs.addFormRef.resetFields()
    },
    // 提交添加餐参数
    submitAddParam(){
    this.$refs.addFormRef.validate(async flag=>{
      if(flag)
      {
        const {data:res}=await this.$axios.post(`categories/${this.cateId}/attributes`,{
          attr_name:this.addForm.attr_name,
          attr_sel:this.activeName
        })
         if(res.meta.status!=201)return this.$message.error('添加失败')
         this.$message.success('添加成功')
        this.addParamDialogVisible=false;
          this.getParams()
      }
    })
    },
    // 关闭编辑参数对话框
    editParamClose(){
      this.$refs.editFormRef.resetFields()
    },
    // 显示编辑参数对话框
    async showEditParamDialog(attr_id){
        const {data:res}=await this.$axios.get(`categories/${this.cateId}/attributes/${attr_id}`,{params:{
            attr_sel:this.activeName
          }})
        if(res.meta.status!=200)return this.$message.error('获取数据失败')
        this.editForm=res.data
        this.editParamDialogVisible=true;
    },
    // 编辑参数提交
    submitEditParam(){
       this.$refs.editFormRef.validate(async flag=>{
        if(flag)
        {
         const {data:res}=await this.$axios.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`,{attr_name:this.editForm.attr_name,attr_sel:this.activeName})
          if(res.meta.status!=200)return this.$message.error('提交失败')
          this.$message.success('修改成功')
          this.getParams()
          this.editParamDialogVisible=false;
        }
       })
    },
    // 根据attr_id删除参数
    deleteParamById(attr_id){
      this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
         const {data:res}=await this.$axios.delete(`categories/${this.cateId}/attributes/${attr_id}`)
        if(res.meta.status!=200)return this.$message.error('删除失败')
              this.$message.success('删除成功')
              this.getParams()
        }).catch(() => {
          this.$message('已取消删除');          
        });
    
    },
    showInput(row){
    row.inputVisible=true;
    // 当前组件渲染完成
    this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
    },
    // 标签失焦事件
    async handleInputConfirm(row){
      if(row.inputValue.trim().length!=0)
      {
        row.attr_vals.push(row.inputValue)
       this.saveAttrVals(row);
      }
      row.inputVisible=false;
      row.inputValue='';
      },
      // 关闭标签事件
      async closeParamTag(row,i){
        row.attr_vals.splice(i,1)
        this.saveAttrVals(row);
      },
      // 封装编辑和删除参数事件
      async saveAttrVals(row){
        const {data:res}=await this.$axios.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{attr_name:row.attr_name,attr_sel:this.activeName,attr_vals:row.attr_vals.join(' ')})
        if(res.meta.status!=200)return this.$message.error('编辑失败')
          this.$message.success('编辑成功')
      }
  },
  computed:{
    //   是否显示按钮
      isdisabled(){
       return this.cascaderValue.length!=3
      },
    //   三级分类id
      cateId(){
          if(this.cascaderValue.length!=3){
           return '';
          }
           return this.cascaderValue[this.cascaderValue.length-1]
       },
      //  对话框标题
       title(){
        return this.activeName=='many'?'动态参数':'静态属性'
       }
      }
  }

</script>

<style scoped lang='less'>
.selectCate{
    margin: 20px 0;
}
.input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
